﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

using VxiConfiguration;

namespace VxiServer
{
    public abstract class TcpCommunication
    {
        
        protected abstract int Port { get; }
        private TcpListener serverSocket;


        public void Start()
        {
            IPAddress addr = IPAddress.Parse(VxiSettings.Settings.ServerIp);
            serverSocket = new TcpListener(addr, Port);
            serverSocket.Start();
            
            Thread ctThread = new Thread(RequestAccept);
            ctThread.Start();
        }

        private void RequestAccept()
        {
            while (true)
            {
                try
                {
                    TcpClient clientSocket = serverSocket.AcceptTcpClient();
                    if (clientSocket.Connected)
                    {
                        NetworkStream networkStream = clientSocket.GetStream();
                        byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];                        
                        networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);

                        byte[] sendBytes = ProccessClientRequest(clientSocket, bytesFrom);

                        if (sendBytes != null && sendBytes.Length > 0)
                        {
                            networkStream.Write(sendBytes, 0, sendBytes.Length);
                        }
                        networkStream.Flush();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" >> " + ex.ToString());
                }
            }
        }

        protected abstract byte[] ProccessClientRequest(TcpClient client, byte[] request);
    }
}
